package mvp.hibernate.demo.controller;

import mvp.hibernate.demo.model.Event;
import mvp.hibernate.demo.model.Money;
import mvp.hibernate.demo.model.Player;
import mvp.hibernate.demo.model.SomeData;
import mvp.hibernate.demo.util.HibernateUtil;
import org.hibernate.Session;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by user on 29.06.2014.
 */
public class PlayerManager {
    public void saveData() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Player player1 = new Player(1, "Vasya", new Money(new BigDecimal(10), Currency.getInstance(Locale.CANADA)));
        Player player2 = new Player(2, "Petya", new Money(new BigDecimal(100), Currency.getInstance(Locale.UK)));
        Player player3 = new Player(3, "Kolya", new Money(new BigDecimal(1000), Currency.getInstance(Locale.US)));
        session.save(player1);
        session.save(player2);
        session.save(player3);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2012);
        Event event1 = new Event("event1", cal, new SomeData(1, 2));
        cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2013);
        Event event2 = new Event("event2", cal, new SomeData(3, 4));

        session.save(event1);
        session.save(event2);

        session.getTransaction().commit();
    }


    public void addEventToPlayer(long playerId, long eventId) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Player player = (Player) session.load(Player.class, playerId);
        Event event = (Event) session.load(Event.class, eventId);
        player.addEvent(event);
        session.getTransaction().commit();
    }

    public Set<Event> getPlayerEvents(long playerId) {
        Set<Event> toSend;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Player player = (Player) session.load(Player.class, playerId);
        session.update(player);
        toSend = player.getEvents();
        player.getPhones().add("0900876433");
        session.getTransaction().commit();
        return toSend;
    }

    public List getAllPlayers(){
        List toSend = null;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        toSend = session.createCriteria(Player.class).list();
        session.getTransaction().commit();
        return toSend;
    }


}
